function [lambda,dminusa] = findparameters(diff0,diff1,q,herdingtype,contrariantype)
% This function calculates the parameters associated with cutoff prices
% that describe herding and contrarian behavior. It returns lambda (loss
% aversion) and delta-alpha (curvature). For herding behavior, we assume 
% delta=1, and for contrarian behavior, we assume alpha=1.

% There is an associated range of parameters associated with each cutoff
% because the actual cutoff may lie anywhere within the interval between
% two threshold prices. diff0 and diff1 represent the highest possible
% cutoff so each could be one signal difference less.

% For herding, we report the parameters associated with the largest
% possible alpha. This corresponds to the smallest possible deltaprime.
% deltaprime also must between 0 and 1 (strictly) to ensure alpha between
% 0 and 1.

% For contrarian, we report the parameters associated with the largest
% possible delta. This corresponds to the largest possible deltaprime.
% deltaprime must also be strictly negative and bounded away from -Inf.

% deltaprime is increasing in the sum but discontinuous at 0, approaching
% Inf from the left and -Inf from the right.
if herdingtype ==1
    % to keep deltaprime between 0 and 1, the sum of differences must be
    % <-2
    if diff0+diff1 >=0
        error('No possible herding parameters.');
    else
        % make cutoffs as small as possible to make deltaprime as small as
        % possible
        diff0 = diff0 - 1;
        diff1 = diff1 - 1;
    end
else
    % to keep deltaprime between -Inf and 0, the sum of differences must be
    % >0
    if diff0+diff1 <=0
        error('No possible contrarian parameters.');
    else
        % do nothing, deltaprime is already as large as possible at the
        % highest possible cutoffs
    end
end 

lambdaprime = sqrt((q/(1-q))^(diff1-diff0));
deltaprime = -2/(diff0+diff1);
if herdingtype == 1
    % delta = 1
    lambda = lambdaprime^deltaprime;
    dminusa = deltaprime;
elseif contrariantype == 1
    % alpha = 1
    dminusa = 1/(1-deltaprime)-1;
    lambda = lambdaprime^dminusa;
else
    dminusa = 0;
    lambda = 1;
end

% checks
if lambda<1
    error('Lambda is too small');
end
if (herdingtype==1 && (dminusa <= 0 || dminusa >=1))
    error('Delta-alpha is out of range for herding type.');
end
if (contrariantype==1 && (dminusa >= 0 || dminusa <= -1))
    error('Delta-alpha is out of range for contrarian type.');
end
